﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using Aptech.UI;
using System.Net;
using System.Net.Sockets;
using System.Threading;
//using System.Windows.Forms.Timer;

namespace ChatQQ
{
    public partial class MainQQForm : Form
    {
        ArrayList lbls = new ArrayList();
        NetworkStream nws;
        public TcpClient client = DlForm.client;
        String uid;
        String pwd;
        ArrayList cts = new ArrayList();
        public String myname = "";
        //String name;
        Thread t1;
        System.Windows.Forms.Timer tface;
        Socket socke;
        Hashtable userform = new Hashtable();
        Hashtable hmessage = new Hashtable();
        //Hashtable faset = new Hashtable();
        Hashtable faces = new Hashtable();
        Hashtable img = new Hashtable();
        bool usings=false;
        public Hashtable userni = new Hashtable();
        bool ishide = false;
        bool isout = false;
        bool softis = false;
        public MainQQForm(string uid,string pwd)
        {
            this.uid = uid;
            this.pwd = pwd;
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            sideBar1.AddGroup("我的好友");
            sideBar1.AddGroup("陌生人");
            this.Text = uid;
            lblname.Text = myname;
        }

        private void MainQQForm_Load(object sender, EventArgs e)
        {
            cbosta.SelectedIndex = 0;
            socke = client.Client;
            nws = new NetworkStream(socke);
            t1 = new Thread(new ThreadStart(clientlisten));
            t1.Start();
            tface = new System.Windows.Forms.Timer();
            tface.Tick += new EventHandler(tface_Tick);
            tface.Start();
            tface.Interval = 700;
            System.Windows.Forms.Timer trmref = new System.Windows.Forms.Timer();
            trmref.Interval = 5000;
            trmref.Tick += new EventHandler(trmref_Tick);
            trmref.Start();
        }

        void trmref_Tick(object sender, EventArgs e)
        {
            try
            {
                string send = "ref" + "|" + uid + "|down";//刷新好友列表
                byte[] chat = Encoding.Default.GetBytes(send.ToCharArray());
                nws.Write(chat, 0, chat.Length);
            }
            catch (Exception)
            {
                
            }
            
        }

        private void btnhead_Click(object sender, EventArgs e)
        {
            
        }

        private void sideBar1_ItemDoubleClick(SbItemEventArgs e)
        {
            String tuid=sideBar1.SeletedItem.Tag.ToString();
            //name = sideBar1.SeletedItem.Text;
            if (!(sideBar1.SeletedItem.ImageIndex%2==0))
            {
                sideBar1.SeletedItem.ImageIndex = sideBar1.SeletedItem.ImageIndex - 1;
            }
            foreach (String var in cts)
            {
                if (tuid == var)
                {
                    return;
                }
            }
            cts.Add(tuid);
            string messages="";
            bool test = false;
            try
            {
                messages = hmessage[tuid].ToString();
                test = true;
            }
            catch (Exception)
            {
                
            }
            ChatForm cf = new ChatForm(uid, tuid, messages, this);
            userform.Add(tuid.ToString(),cf);
            if (test)
            {
                hmessage[tuid] = "";
            }
            cf.Show();
            faces.Remove(tuid);
        }


        private void thisclose()
        {
            try
            {
                nws = client.GetStream();
                string send = "off" + "|" + uid+"|down";//下线
                byte[] chat = Encoding.Default.GetBytes(send.ToCharArray());
                nws.Write(chat, 0, chat.Length);
                t1.Abort();
            }
            catch (Exception)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        private void MainQQForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            thisclose();
            Application.Exit();
        }

        private void clientlisten()
        {
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[2048];
                    socke.Receive(buffer);
                    String cmd = Encoding.Default.GetString(buffer);
                    String[] message = cmd.Split(new char[] { '|' }, 3);
                    bool heve = false;
                    if (message[0] == "say")//=====================================接收消息==========================================
                    {
                        String uname = userni[message[1].ToString()].ToString();
                        foreach (String var in cts)
                        {
                            if (var == message[1])
                            {
                                ((ChatForm)userform[message[1].ToString()]).rtxbs.AppendText("\r\n" + uname + "  " + DateTime.Now + "\r\n" + message[2] + "\r\n");
                                ((ChatForm)userform[message[1].ToString()]).rtxbs.ScrollToCaret();
                                heve = true;
                            }
                            
                        }
                        if (heve==false)
                        {
                            string messages = "\r\n" + uname + "  " + DateTime.Now + "\r\n" + message[2] + "\r\n";
                            
                            try
                            {
                                hmessage.Add(message[1].ToString(), messages);
                                try
                                {
                                    faces.Add(message[1].ToString(), message[1].ToString());

                                }
                                catch (Exception)
                                {

                                }
                                
                            }
                            catch (Exception)
                            {
                                string mtemp = hmessage[message[1].ToString()].ToString() .Trim();
                                string temp = mtemp.Trim(new char[]{'\0'})+ "\r\n" + uname + "  " + DateTime.Now + "\r\n" + message[2] + "\r\n";
                                hmessage[message[1].ToString()]=temp;
                                try
                                {
                                    faces.Add(message[1].ToString(), message[1].ToString());

                                }
                                catch (Exception)
                                {
                                    
                                }
                                
                            }
                        }
                    }//=====================================接收消息==========================================
                    //=====================================初始化信息===========================================
                    else if (message[0]=="my")
                    {
                        ference(message[1]);
                    }
                    //=====================================初始化信息===========================================
                    //=====================================刷新好友信息===========================================
                    else if (message[0] == "refa")
                    {
                        reference(message[1]);
                    }
                    
                }
                catch (Exception)
                {
                    //MessageBox.Show(ex.Message);
                }
            }
            
        }

       private void tface_Tick(object sender, EventArgs e)
        {
            for (int n = 0; n < faces.Count; n++)
            {
                for (int i = 0; i < sideBar1.Groups[0].Items.Count; i++)
                {
                    if (usings!=false)
                    {
                        break;
                    }
                    SbItem var = sideBar1.Groups[0].Items[i];
                    try
                    {
                        if (var.Tag.ToString()== (faces[var.Tag.ToString()].ToString()))
                        {
                            if (var.ImageIndex==Int32.Parse(img[var.Tag.ToString()].ToString()))
                            {
                                var.ImageIndex = var.ImageIndex + 1;
                            }
                            else
                            {
                                var.ImageIndex = var.ImageIndex - 1;
                            }
                            sideBar1.Refresh();
                       }
                    }
                    catch (Exception)
                    {
                        //MessageBox.Show(ex.Message);
                    }
                }
                
            } 
        }
        public void removect(string no)
        {
            foreach (String var in cts)
            {
                if (var == no)
                {
                    cts.Remove(no);
                    break;
                }
            }
            userform.Remove(no);
        }

        private void tmrface_Tick(object sender, EventArgs e)
        {
            //MessageBox.Show("");
        }

        private void ference(string fm)
        {
            if (softis==false)
            {
                try
                {
                    SbItem item = null;
                    string[] fmessage = fm.Split(new char[] { '&' });
                    for (int i = 0; i < fmessage.Length; i++)
                    {
                        string[] fmtemp = fmessage[i].Split(new char[] { '*' });
                        //for (int j = 0; j < fmtemp.Length; j++)
                        //{
                        if (i == 0)
                        {
                            myname = fmtemp[0];
                            lblname.Text = fmtemp[0];
                            toolStrip1.ImageList = imglst;
                            btnhead.ImageIndex = Int32.Parse(fmtemp[1]);
                        }
                        else //if(i>1)
                        {
                            int image = Int32.Parse(fmtemp[2]);
                            if (Int32.Parse(fmtemp[3]) != 1)
                            {
                                image += 200;
                            }
                            string QQNo = fmtemp[0];
                            item = new SbItem(fmtemp[1], image);
                            item.Tag = QQNo;
                            userni.Add(QQNo, fmtemp[1]);
                            sideBar1.Groups[0].Items.Add(item);
                            img.Add(QQNo, image);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else 
            {
                return;
            }
            
            
        }

        private void reference(string fm)
        {
            try
            {
                usings = true;
                string[] fmessage = fm.Split(new char[] { '&' });
                for (int i = 0; i < fmessage.Length; i++)
                {
                    string[] fmtemp = fmessage[i].Split(new char[] { '*' });
                    for (int j = 0; j < sideBar1.Groups[0].Items.Count; j++)
                    {
                        SbItem item = sideBar1.Groups[0].Items[j];
                        if (fmtemp[0] == item.Tag.ToString())
                        {
                            item.Text = fmtemp[1];
                            item.ImageIndex = Int32.Parse(fmtemp[2]);
                            img[fmtemp[0]] = Int32.Parse(fmtemp[2]);
                            if (Int32.Parse(fmtemp[3]) != 1)
                            {
                                item.ImageIndex = Int32.Parse(fmtemp[2]) + 200;
                            }
                        }
                    }

                }
                usings = false;
                sideBar1.Refresh();
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }

        private void cbosta_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            try
            {
                if (cbosta.SelectedIndex == 2)
                {
                    thisclose();
                    isout = true;
                    softis = true;
                }
                else if (cbosta.SelectedIndex == 0)
                {
                    if (ishide)
                    {
                        string send = "hide" + "|" + uid + "|";//隐身
                        byte[] chat = Encoding.Default.GetBytes(send.ToCharArray());
                        nws.Write(chat, 0, chat.Length);
                        ishide = false;
                    }
                    else if (isout)
                    {
                        client = new TcpClient("192.168.1.2", 8098);
                        nws = client.GetStream();
                        string send = "in" + "|" + uid + "|" + pwd;//上线
                        byte[] chat = Encoding.Default.GetBytes(send.ToCharArray());
                        nws.Write(chat, 0, chat.Length);
                        socke = client.Client;
                        nws = new NetworkStream(socke);
                        t1 = new Thread(new ThreadStart(clientlisten));
                        t1.Start();
                        isout = false;
                    }
                    ishide = false;
                }
                else if (cbosta.SelectedIndex == 1)
                {
                    ishide = true;
                    string send = "hide" + "|" + uid + "|";//隐身
                    byte[] chat = Encoding.Default.GetBytes(send.ToCharArray());
                    nws.Write(chat, 0, chat.Length);
                    
                }
            }
            catch (Exception)
            {
                //MessageBox.Show(ex.Message);
            }
            
        }

        private void smnumin_Click(object sender, EventArgs e)
        {
            sideBar1.View = SbView.SmallIcon;
        }

        private void smnumax_Click(object sender, EventArgs e)
        {
            sideBar1.View = SbView.LargeIcon;
        }

        private void smnudelf_Click(object sender, EventArgs e)
        {
            SbItem item = sideBar1.SeletedItem;
            if (item==null)
            {
                MessageBox.Show("你没有选择任何好友！","错误提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                return;
            }
            DialogResult quest = MessageBox.Show("你确定要删除该好友吗？","删除确认",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
            if (quest==DialogResult.No)
            {
                return;
            }
            
            string duid = item.Tag.ToString();
            try
            {
                sideBar1.Groups[0].Items.Remove(item);
                string send = "del" + "|" + uid + "|"+duid;//刷新好友列表
                byte[] chat = Encoding.Default.GetBytes(send.ToCharArray());
                nws.Write(chat, 0, chat.Length);
            }
            catch (Exception)
            {

            }
        }
    }
}